﻿using Common;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Razor.TagHelpers;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using FastAPI.WebApiHelper;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Kingdee.BOS.Core.CloudModel;
using Kingdee.BOS.Core.CloudModel.Crm;
using Kingdee.BOS.Core.CloudModel.Cloud;
using Kingdee.BOS.Core.CloudModel.DSPT;
using Microsoft.Extensions.Configuration;
using System.IO;
using MethodSetBus;


namespace FastAPI.Controllers
{



    [ApiController]
    [Route("CloudApi")]

    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        static WeatherForecastController()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json");

            IConfigurationRoot config = builder.Build();
            CrmUrl = config["CrmNetworkInfo:CrmUrl"];
            Crmcode = config["CrmNetworkInfo:code"];

            CommUrl = config["ECOMMERCEInfo:ECOMMUrl"];
            usename = config["ECOMMERCEInfo:username"];
            usepassword = config["ECOMMERCEInfo:userpassword"];
            CommDBId = config["ECOMMERCEInfo:DBId"];
            CommType = config["ECOMMERCEInfo:Type"];

            TaskTime = config["ECOMMERCEInfo:TaskTime"];

        }

        public static string CrmUrl = null;
        public static string Crmcode = null;

        public static string CommUrl = null;
        public static string usename = null;
        public static string usepassword = null;
        public static string CommDBId = null;
        public static Dictionary<string, string> Header = null;
        public static string CommType = null;

        public static string TaskTime = null;


        public static DateTime CreateDate = DateTime.Now;


        /// <summary>
        /// 控制台打印信息
        /// </summary>
        /// <param name="bol">打印类型 A 通过 B 错误 C 异常</param>
        /// <param name="TopTxt">打印头</param>
        /// <param name="Text">打印详情</param>
        public void ConsoleWrite(string bol, string TopTxt, string Text)
        {
            string Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            if (bol == "A")
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.Write(Date + TopTxt);
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine(Text);
            }
            else if (bol == "B")
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.Write(Date + TopTxt);
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine(Text);
            }
            else if (bol == "C")
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.Write(Date + TopTxt);
                Console.WriteLine(Text);
            }
        }


        #region 测试接口
        [Route("GetText"), HttpGet]
        public async Task<IEnumerable<WeatherForecast>> Get()
        {
            //查询
            DataTable dt = DBHelper.ExecuteQuery("select top 1 * from T_BD_MATERIAL; ");
            DataTable dt2 = new DataTable();//LogHelper.ExecuteQuery("select top 1 * from FNeedsTbaleTwo; ");
            //写数据库
            //int rs = LogHelper.WriteLog("fbn0001", "1465468767", "{sdfs:safdsf}", "{awerwerwer:werewrewr}");
            //post请求
            //string httprs = await WebHelper.HttpPost("http://367993d2.r5.vip.cpolar.cn/admin/login/loginApi", Newtonsoft.Json.JsonConvert.SerializeObject(new
            //{
            //	login_name = "张泽龙",
            //	password = "topking2001",
            //	type = 1,
            //	region = 1
            //}), null);
            try
            {
                string httprs = await WebHelper.HttpPost("http://zhyphsy.gnway.cc:54202/ceshi/crmapi/apiKey.php?authen_code=3AC38B5F", null, null, "multipart/form-data");
            }
            catch (Exception e)
            {
                throw;
            }



            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }


        /// <summary>
        /// 获取测试Json
        /// </summary>
        /// <param name="Type">Json类型</param>
        /// <returns></returns>
        [Route("MaterialJson"), HttpPost]
        public string MaterialJson(string Type)
        {
            switch (Type)
            {
                case "物料":
                    Crm_MaterialList _Data = new Crm_MaterialList();
                    _Data.product_no = "CS1000001";//物料编码
                    _Data.productname = "测试测试";//产品名称
                    _Data.productcode = "CSRGB00001";//编码或条码
                    _Data.productcategory = "大米";//产品类别
                    _Data.productsheet = "15kg";//规格型号
                    _Data.unit_price = "15";//产品报价(RMB)
                    _Data.procostprice = "12";//参考成本价(RMB)
                    _Data.qtyinstock = "100";//总库存数量
                    _Data.qtyearly = "10";//安全库存
                    _Data.description = "测试测试"; //备注
                    _Data.discontinued = "1";//禁用
                    _Data.productdetails = "1";//产品详情
                    _Data.usageunit = "个";//计量单位
                    _Data.promodifiedby = "卢红霞";//修改人
                    _Data.prosmownerid = "卢红霞"; //负责人
                    _Data.smcreatorid = "卢红霞";//创建人
                    return JsonConvert.SerializeObject(_Data);
                    break;
                case "客户":
                    Crm_Accounts _Accounts = new Crm_Accounts();
                    _Accounts.account_no = "CSKH100001";
                    _Accounts.accountname = "测试测试666";
                    _Accounts.phone = "13868786981";//13868786981
                    _Accounts.email = "";//ceshi@yid.cn
                    _Accounts.website = "";
                    _Accounts.rating = "";
                    _Accounts.leadsource = "";
                    _Accounts.industry = "";
                    _Accounts.bill_country = "";
                    _Accounts.bill_state = "";
                    _Accounts.bill_city = "";
                    _Accounts.bill_area = "";
                    _Accounts.description = "";
                    _Accounts.assigned_user_id = "";
                    return JsonConvert.SerializeObject(_Accounts);
                    break;
                case "SAL_SaleOrder":
                    DataType<SaleOrder_OutStock> data = new DataType<SaleOrder_OutStock>();
                    data.Type = Type;
                    data.Data = new SaleOrder_OutStock();
                    SaleOrder_OutStock order_OutStock = new SaleOrder_OutStock();
                    order_OutStock.FNumber = "2023062000001";
                    order_OutStock.FDate = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                    order_OutStock.FOrgNo = "100";
                    order_OutStock.FOrgName = "武汉";
                    order_OutStock.FCustomerNo = "CUST0301";
                    order_OutStock.FCustomerName = "电商平台";
                    order_OutStock.FSaleSpersonNo = "";
                    order_OutStock.FSaleSpersonName = "";
                    order_OutStock.FAddress = "湖北省武汉市武昌区湖北武汉秦园路徐家棚街道油料所社区3-2-502";
                    order_OutStock.FPhoneNumber = "13868789688";
                    order_OutStock.Entity = new List<SaleOrder_OutStockEntry>();
                    SaleOrder_OutStockEntry order_OutStockEntry = new SaleOrder_OutStockEntry();
                    order_OutStockEntry.FMaterialNo = "AXP-XX-003";
                    order_OutStockEntry.FMaterialName = "瑞士莲盒装巧克力（红）200g（原装进口）";
                    order_OutStockEntry.FPrice = 10;
                    order_OutStockEntry.FQty = 5;
                    order_OutStockEntry.FSubtotal = 50;
                    order_OutStockEntry.FUnitNo = "Pcs";
                    order_OutStockEntry.FUnitName = "Pcs";
                    order_OutStockEntry.FStockNo = "CK001";
                    order_OutStockEntry.FStockName = "总仓";
                    order_OutStock.Entity.Add(order_OutStockEntry);
                    order_OutStockEntry = new SaleOrder_OutStockEntry();
                    order_OutStockEntry.FMaterialNo = "2022-12-DZWL-015";
                    order_OutStockEntry.FMaterialName = "一冶机关工会定制包装箱";
                    order_OutStockEntry.FPrice = 10;
                    order_OutStockEntry.FQty = 10;
                    order_OutStockEntry.FSubtotal = 100;
                    order_OutStockEntry.FUnitNo = "08";
                    order_OutStockEntry.FUnitName = "个";
                    order_OutStockEntry.FStockNo = "CK001";
                    order_OutStockEntry.FStockName = "总仓";
                    order_OutStock.Entity.Add(order_OutStockEntry);
                    data.Data = order_OutStock;
                    return JsonConvert.SerializeObject(data);
                    break;
                case "SAL_OutStock":
                    DataType<SaleOrder_OutStock> data2 = new DataType<SaleOrder_OutStock>();
                    data2.Type = Type;
                    data2.Data = new SaleOrder_OutStock();
                    SaleOrder_OutStock _order_OutStock = new SaleOrder_OutStock();
                    _order_OutStock.FNumber = "2023062000001";
                    _order_OutStock.FDate = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                    _order_OutStock.FOrgNo = "100";
                    _order_OutStock.FOrgName = "湖北源盛";
                    _order_OutStock.FCustomerNo = "CUST0301";
                    _order_OutStock.FCustomerName = "电商平台";
                    _order_OutStock.FSaleSpersonNo = "";
                    _order_OutStock.FSaleSpersonName = "";
                    _order_OutStock.FAddress = "湖北省武汉市武昌区湖北武汉秦园路徐家棚街道油料所社区3-2-502";
                    _order_OutStock.FPhoneNumber = "13868789688";
                    _order_OutStock.Entity = new List<SaleOrder_OutStockEntry>();
                    SaleOrder_OutStockEntry _order_OutStockEntry = new SaleOrder_OutStockEntry();
                    _order_OutStockEntry.FMaterialNo = "AXP-XX-003";
                    _order_OutStockEntry.FMaterialName = "瑞士莲盒装巧克力（红）200g（原装进口）";
                    _order_OutStockEntry.FPrice = 10;
                    _order_OutStockEntry.FQty = 5;
                    _order_OutStockEntry.FSubtotal = 50;
                    _order_OutStockEntry.FUnitNo = "Pcs";
                    _order_OutStockEntry.FUnitName = "Pcs";
                    _order_OutStockEntry.FStockNo = "CK001";
                    _order_OutStockEntry.FStockName = "总仓";
                    _order_OutStock.Entity.Add(_order_OutStockEntry);
                    data2.Data = _order_OutStock;
                    return JsonConvert.SerializeObject(data2);
                    break;
                case "SAL_RETURNSTOCK":
                    DataType<SaleOrder_OutStock> data3 = new DataType<SaleOrder_OutStock>();
                    data3.Type = Type;
                    data3.Data = new SaleOrder_OutStock();
                    SaleOrder_OutStock _order_OutStock1 = new SaleOrder_OutStock();
                    _order_OutStock1.FNumber = "XSCKD000064";
                    _order_OutStock1.FDate = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                    _order_OutStock1.FOrgNo = "100";
                    _order_OutStock1.FOrgName = "湖北源盛";
                    _order_OutStock1.FCustomerNo = "CUST0301";
                    _order_OutStock1.FCustomerName = "电商平台";
                    _order_OutStock1.FSaleSpersonNo = "";
                    _order_OutStock1.FSaleSpersonName = "";
                    _order_OutStock1.FAddress = "湖北省武汉市武昌区湖北武汉秦园路徐家棚街道油料所社区3-2-502";
                    _order_OutStock1.FPhoneNumber = "13868789688";
                    _order_OutStock1.Entity = new List<SaleOrder_OutStockEntry>();
                    SaleOrder_OutStockEntry _order_OutStockEntry1 = new SaleOrder_OutStockEntry();
                    _order_OutStockEntry1.FMaterialNo = "AXP-XX-003";
                    _order_OutStockEntry1.FMaterialName = "瑞士莲盒装巧克力（红）200g（原装进口）";
                    _order_OutStockEntry1.FPrice = 10;
                    _order_OutStockEntry1.FQty = 5;
                    _order_OutStockEntry1.FSubtotal = 50;
                    _order_OutStockEntry1.FUnitNo = "Pcs";
                    _order_OutStockEntry1.FUnitName = "Pcs";
                    _order_OutStockEntry1.FStockNo = "CK001";
                    _order_OutStockEntry1.FStockName = "总仓";
                    _order_OutStock1.Entity.Add(_order_OutStockEntry1);
                    data3.Data = _order_OutStock1;
                    return JsonConvert.SerializeObject(data3);
                    break;
                default:
                    return "请输入有效类型！";
                    break;
            }

        }

        [Route("CSCSCS"), HttpPost]
        public string CSJsonApi(OrgBase orgBase)
        {
            object obj = orgBase.FNumber;
            return obj.ToString();
        }
        #endregion


        #region 1.金蝶相关业务
        public string DatetimeUnle()
        {
            DateTime LastDate = DateTime.Now;
            TimeSpan span = CreateDate - LastDate;
            return $"本次耗时:(耗时:{span.TotalSeconds.ToString()}秒)";
        }


        /// <summary>
        /// 写入金蝶-销售
        /// </summary>
        /// <returns></returns>
        [Route("CloudSave"), HttpPost]
        public string Kingdee_Save(DataType<SaleOrder_OutStock> TypeData)
        {
            IsSuccessResult isSuccess = new IsSuccessResult();
            OperateParamBus operateParam = new OperateParamBus();
            string RootJson = "";
            string BillType = "";
            try
            {
                if (TypeData.Data == null)
                {
                    ConsoleWrite("A", TypeData.Type + "-Data:", "数据为空！");
                    isSuccess.Code = 100;
                    isSuccess.Result = null;
                    isSuccess.Message = "请传入正确的数据Json！";
                    return JsonConvert.SerializeObject(isSuccess);
                }
                SaleOrder_OutStock order_OutStock = TypeData.Data;
                if (order_OutStock == null)
                {
                    ConsoleWrite("A", TypeData.Type + "-Data:", "数据为空！");
                    isSuccess.Code = 100;
                    isSuccess.Result = null;
                    isSuccess.Message = "请传入正确的数据Json！";
                    return JsonConvert.SerializeObject(isSuccess);
                }
                var LoginResult = InvokeHelper.Login();
                TxtHelper.LogWrite(TypeData.Type + "登录返回：" + LoginResult);
                var isLogin = JObject.Parse(LoginResult)["LoginResultType"].Value<int>();
                var LoginMessage = JObject.Parse(LoginResult)["Message"].Value<string>();
                if (isLogin == 1)
                {
                    switch (TypeData.Type)
                    {
                        case "SAL_SaleOrder":
                            DataTable dtRow = DBHelper.ExecuteQuery($"select count(1) cnt from T_SAL_ORDER where F_PFKX_LARGETEXT1='{order_OutStock.FNumber}' and FCancelStatus='A'");
                            if (Convert.ToInt32(dtRow.Rows[0][0]) > 0)
                            {
                                isSuccess.Code = 500;
                                isSuccess.Result = null;
                                isSuccess.Message = $"电商编号{order_OutStock.FNumber}在金蝶已存在，请处理后在操作！";
                                ConsoleWrite("B", "订单保存:", JsonConvert.SerializeObject(isSuccess));
                                return JsonConvert.SerializeObject(isSuccess);
                            }
                            for (int i = 0; i < order_OutStock.Entity.Count; i++)
                            {
                                string SqlEntry = $"select a.FNumber from T_BD_MATERIAL a left join T_ORG_ORGANIZATIONS org on a.FUSEORGID=org.FORGID where a.FDOCUMENTSTATUS='C' and a.FForbidStatus ='A' and a.FNUMBER='{order_OutStock.Entity[i].FMaterialNo}' and org.FNUMBER='{order_OutStock.FOrgNo}'";
                                DataTable dtentry = DBHelper.ExecuteQuery(SqlEntry);
                                if (dtentry.Rows.Count <= 0)
                                {
                                    isSuccess.Code = 500;
                                    isSuccess.Result = null;
                                    isSuccess.Message = $"物料编码{order_OutStock.Entity[i].FMaterialNo}在金蝶不存在！！！";
                                    ConsoleWrite("B", "订单保存:", JsonConvert.SerializeObject(isSuccess));
                                    return JsonConvert.SerializeObject(isSuccess);
                                }
                            }


                            SAL_SaleOrderBus _SaleOrderBus = new SAL_SaleOrderBus();
                            IsSuccessResult isres = _SaleOrderBus.IsNullClounm(TypeData);
                            if (isres.Code != 0)
                            {
                                isSuccess.Code = 100;
                                isSuccess.Result = null;
                                isSuccess.Message = isres.Message;
                                return JsonConvert.SerializeObject(isSuccess);
                            }
                            RootJson = _SaleOrderBus.Get_SQL_AaleOrder(order_OutStock);
                            BillType = "销售订单";
                            break;
                        case "SAL_OutStock":
                            for (int i = 0; i < order_OutStock.Entity.Count; i++)
                            {
                                DataTable dt = DBHelper.ExecuteQuery("select a.FID,FBILLNO,a.FOBJECTTYPEID,b.FENTRYID,b.FSEQ,'SaleOrder-OutStock' as FRuleId,'T_SAL_ORDERENTRY' as TableName from T_SAL_ORDER a " +
                                      "left join T_SAL_ORDERENTRY b on a.FID=b.FID " +
                                      "left join T_BD_MATERIAL c on b.FMATERIALID=c.FMATERIALID " +
                                      "where a.F_PFKX_LARGETEXT1='" + order_OutStock.FNumber + "' and c.FNUMBER='" + order_OutStock.Entity[i].FMaterialNo + "' and a.FDOCUMENTSTATUS='C' and a.FCancelStatus='A'");
                                if (dt.Rows.Count <= 0 || dt == null)
                                {
                                    isSuccess.Code = 500;
                                    isSuccess.Result = null;
                                    isSuccess.Message = "明细出现无关联数据！";
                                    return JsonConvert.SerializeObject(isSuccess);
                                }
                            }
                            SAL_OutStockBus _OutStockBus = new SAL_OutStockBus();
                            IsSuccessResult isOut = _OutStockBus.IsNullClounm(TypeData);
                            if (isOut.Code != 0)
                            {
                                isSuccess.Code = 100;
                                isSuccess.Result = null;
                                isSuccess.Message = isOut.Message;
                                return JsonConvert.SerializeObject(isSuccess);
                            }
                            RootJson = _OutStockBus.Get_SAL_OutStock(order_OutStock);
                            BillType = "销售出库";
                            break;
                        case "SAL_RETURNSTOCK":
                            DataTable stBill = DBHelper.ExecuteQuery($"exec Get_OUTSTOCKBillData '{order_OutStock.FNumber}'");
                            if (stBill == null || stBill.Rows.Count <= 0)
                            {
                                isSuccess.Code = 500;
                                isSuccess.Result = null;
                                isSuccess.Message = $"关联出库单编号{order_OutStock.FNumber}不存在！";
                                return JsonConvert.SerializeObject(isSuccess);
                            }
                            for (int i = 0; i < order_OutStock.Entity.Count; i++)
                            {
                                string sql = string.Format("select a.FID,a.FBILLNO,a.FOBJECTTYPEID,b.FENTRYID,b.FSEQ,w.FNUMBER from T_SAL_OUTSTOCK a " +
                                    "left join T_SAL_OUTSTOCKENTRY b on a.FID=b.FID " +
                                    "left join T_BD_MATERIAL w on b.FMATERIALID=w.FMATERIALID " +
                                    "where FBILLNO='{0}' and w.FNUMBER='{1}' ", order_OutStock.FNumber, order_OutStock.Entity[i].FMaterialNo);
                                DataTable dt = DBHelper.ExecuteQuery(sql);
                                if (dt.Rows.Count <= 0 || dt == null)
                                {
                                    isSuccess.Code = 500;
                                    isSuccess.Result = null;
                                    isSuccess.Message = "明细出现无关联数据！";
                                    return JsonConvert.SerializeObject(isSuccess);
                                }
                            }
                            SAL_RETURNSTOCKBus _RETURNSTOCKBus = new SAL_RETURNSTOCKBus();
                            IsSuccessResult isRetuen = _RETURNSTOCKBus.IsNullClounm(TypeData);
                            if (isRetuen.Code != 0)
                            {
                                isSuccess.Code = 100;
                                isSuccess.Result = null;
                                isSuccess.Message = isRetuen.Message;
                                return JsonConvert.SerializeObject(isSuccess);
                            }
                            RootJson = _RETURNSTOCKBus.Get_ReturnStockData(order_OutStock, stBill);
                            BillType = "销售退货";
                            break;
                        default:
                            isSuccess.Code = 500;
                            isSuccess.Result = null;
                            isSuccess.Message = "请输入有效类型！(Type)";
                            return JsonConvert.SerializeObject(isSuccess);
                            break;
                    }

                    //TxtHelper.LogWrite(TypeData.Type + "保存传入：" + RootJson);
                    string https = InvokeHelper.Save(TypeData.Type, RootJson);//保存
                    FResult result = JsonConvert.DeserializeObject<FResult>(https);
                    if (result.Result.ResponseStatus.IsSuccess)
                    {
                        LogHelper.WriteCloudLog("保存-" + BillType, Convert.ToInt32(result.Result.ResponseStatus.SuccessEntitys[0].Id), result.Result.ResponseStatus.SuccessEntitys[0].Number, 1, "中合写入金蝶", RootJson, https, "");
                        RootJson = operateParam.Get_OperateParam(result.Result.ResponseStatus.SuccessEntitys[0].Id.ToString(), "");
                        https = InvokeHelper.Submit(TypeData.Type, RootJson);//提交
                        result = JsonConvert.DeserializeObject<FResult>(https);
                        if (result.Result.ResponseStatus.IsSuccess)
                        {
                            LogHelper.WriteCloudLog("提交-" + BillType, Convert.ToInt32(result.Result.ResponseStatus.SuccessEntitys[0].Id), result.Result.ResponseStatus.SuccessEntitys[0].Number, 1, "中合写入金蝶", RootJson, https, "");
                            https = InvokeHelper.Audit(TypeData.Type, RootJson);//审核
                            result = JsonConvert.DeserializeObject<FResult>(https);
                            if (result.Result.ResponseStatus.IsSuccess)
                            {
                                LogHelper.WriteCloudLog("审核-" + BillType, Convert.ToInt32(result.Result.ResponseStatus.SuccessEntitys[0].Id), result.Result.ResponseStatus.SuccessEntitys[0].Number, 1, "中合写入金蝶", RootJson, https, "");
                                NeedsResult needs = new NeedsResult();
                                needs.Id = result.Result.ResponseStatus.SuccessEntitys[0].Id;
                                needs.Number = result.Result.ResponseStatus.SuccessEntitys[0].Number;

                                ConsoleWrite("A", TypeData.Type + "-Audit:", JsonConvert.SerializeObject(needs));

                                isSuccess.Code = 0;
                                isSuccess.Result = needs;
                                isSuccess.Message = null;
                                return JsonConvert.SerializeObject(isSuccess);
                            }
                            else
                            {
                                LogHelper.WriteCloudLog("审核-" + BillType, 0, "", 0, "中合写入金蝶", RootJson, https, "");
                                ConsoleWrite("B", TypeData.Type + "-Audit:", JsonConvert.SerializeObject(result.Result.ResponseStatus.Errors[0].Message));

                                InvokeHelper.CancelAssign(TypeData.Type, RootJson);//撤销
                                InvokeHelper.Delete(TypeData.Type, RootJson);//删除

                                isSuccess.Code = 500;
                                isSuccess.Result = null;
                                isSuccess.Message = result.Result.ResponseStatus.Errors[0].Message;
                                return JsonConvert.SerializeObject(isSuccess);
                            }
                        }
                        else
                        {
                            LogHelper.WriteCloudLog("提交-" + BillType, Convert.ToInt32(result.Result.ResponseStatus.SuccessEntitys[0].Id), result.Result.ResponseStatus.SuccessEntitys[0].Number, 0, "中合写入金蝶", RootJson, https, "");
                            ConsoleWrite("B", TypeData.Type + "-Submit:", JsonConvert.SerializeObject(result.Result.ResponseStatus.Errors[0].Message));

                            InvokeHelper.Delete(TypeData.Type, RootJson);//删除

                            isSuccess.Code = 500;
                            isSuccess.Result = null;
                            isSuccess.Message = result.Result.ResponseStatus.Errors[0].Message;
                            return JsonConvert.SerializeObject(isSuccess);
                        }
                    }
                    else
                    {
                        LogHelper.WriteCloudLog("保存-" + BillType, 0, "", 0, "中合写入金蝶", RootJson, https, "");
                        ConsoleWrite("B", TypeData.Type + "-Save:", JsonConvert.SerializeObject(result.Result.ResponseStatus.Errors[0].Message));
                        isSuccess.Code = 500;
                        isSuccess.Result = null;
                        isSuccess.Message = result.Result.ResponseStatus.Errors[0].Message;
                        return JsonConvert.SerializeObject(isSuccess);
                    }
                }
                else
                {
                    ConsoleWrite("B", TypeData.Type + "-Login:", LoginMessage);
                    isSuccess.Code = 500;
                    isSuccess.Result = null;
                    isSuccess.Message = LoginMessage;
                    return JsonConvert.SerializeObject(isSuccess);
                }
            }
            catch (Exception e)
            {
                ConsoleWrite("C", "Save方法异常信息:", e.Message);
                LogHelper.WriteCloudLog("调用-" + BillType, 0, "", 0, "中合写入金蝶", "", "", e.Message);

                isSuccess.Code = 505;
                isSuccess.Result = null;
                isSuccess.Message = "登录失败！";
                return JsonConvert.SerializeObject(isSuccess);
            }
        }


        /// <summary>
        /// 金蝶单据-单据操做（审核、反审核；提交、撤销；删除；作废。）
        /// </summary>
        /// <returns></returns>
        [Route("CloudDocumentOp"), HttpPost]
        public string Kingdee_DocumentOp(DataOpType<NeedsResult> TypeNeeds)
        {
            IsSuccessResult isSuccess = new IsSuccessResult();
            OperateParamBus operateParam = new OperateParamBus();
            try
            {
                if (TypeNeeds == null || TypeNeeds.Data == null)
                {
                    ConsoleWrite("B", TypeNeeds.Type + "-Data:", "数据为空！");
                    isSuccess.Code = 100;
                    isSuccess.Result = null;
                    isSuccess.Message = "请传入正确的数据Json！";
                    return JsonConvert.SerializeObject(isSuccess);
                }

                string Contout = operateParam.Get_OperateParam(TypeNeeds.Data.Id.ToString(), "");


                var LoginResult = InvokeHelper.Login();
                TxtHelper.LogWrite(TypeNeeds.Type + "登录返回：" + LoginResult);
                var isLogin = JObject.Parse(LoginResult)["LoginResultType"].Value<int>();
                var LoginMessage = JObject.Parse(LoginResult)["Message"].Value<string>();
                if (isLogin == 1)
                {
                    for (int i = 0; i < TypeNeeds.OpType.Count; i++)
                    {
                        switch (TypeNeeds.OpType[i].FNumber)
                        {
                            case "Audit"://审核
                                string https = InvokeHelper.Audit(TypeNeeds.Type, Contout);
                                FResult result = JsonConvert.DeserializeObject<FResult>(https);
                                if (result.Result.ResponseStatus.IsSuccess)
                                {
                                    LogHelper.WriteCloudLog("审核-" + TypeNeeds.Type, Convert.ToInt32(result.Result.ResponseStatus.SuccessEntitys[0].Id), result.Result.ResponseStatus.SuccessEntitys[0].Number, 1, "中合写入金蝶", Contout, https, "");
                                    NeedsResult needs = new NeedsResult();
                                    needs.Id = result.Result.ResponseStatus.SuccessEntitys[0].Id;
                                    needs.Number = result.Result.ResponseStatus.SuccessEntitys[0].Number;

                                    ConsoleWrite("A", TypeNeeds.Type + "-Audit:", JsonConvert.SerializeObject(needs));
                                    isSuccess.Code = 0;
                                    isSuccess.Result = needs;
                                    isSuccess.Message = null;
                                }
                                else
                                {
                                    LogHelper.WriteCloudLog("审核-" + TypeNeeds.Type, 0, "", 0, "中合写入金蝶", Contout, https, "");
                                    ConsoleWrite("B", TypeNeeds.Type + "-Audit:", JsonConvert.SerializeObject(result.Result.ResponseStatus.Errors[0].Message));
                                    isSuccess.Code = 500;
                                    isSuccess.Result = null;
                                    isSuccess.Message = result.Result.ResponseStatus.Errors[0].Message;
                                    return JsonConvert.SerializeObject(isSuccess);
                                }
                                break;
                            case "Submit"://提交
                                https = InvokeHelper.Submit(TypeNeeds.Type, Contout);
                                result = JsonConvert.DeserializeObject<FResult>(https);
                                if (result.Result.ResponseStatus.IsSuccess)
                                {
                                    LogHelper.WriteCloudLog("提交-" + TypeNeeds.Type, Convert.ToInt32(result.Result.ResponseStatus.SuccessEntitys[0].Id), result.Result.ResponseStatus.SuccessEntitys[0].Number, 1, "中合写入金蝶", Contout, https, "");
                                    NeedsResult needs = new NeedsResult();
                                    needs.Id = result.Result.ResponseStatus.SuccessEntitys[0].Id;
                                    needs.Number = result.Result.ResponseStatus.SuccessEntitys[0].Number;

                                    ConsoleWrite("A", TypeNeeds.Type + "-Submit:", JsonConvert.SerializeObject(needs));
                                    isSuccess.Code = 0;
                                    isSuccess.Result = needs;
                                    isSuccess.Message = null;
                                }
                                else
                                {
                                    LogHelper.WriteCloudLog("提交-" + TypeNeeds.Type, 0, "", 0, "中合写入金蝶", Contout, https, "");
                                    ConsoleWrite("B", TypeNeeds.Type + "-Submit:", JsonConvert.SerializeObject(result.Result.ResponseStatus.Errors[0].Message));
                                    isSuccess.Code = 500;
                                    isSuccess.Result = null;
                                    isSuccess.Message = result.Result.ResponseStatus.Errors[0].Message;
                                    return JsonConvert.SerializeObject(isSuccess);
                                }
                                break;
                            case "UnSubmit"://撤销
                                https = InvokeHelper.CancelAssign(TypeNeeds.Type, Contout);
                                result = JsonConvert.DeserializeObject<FResult>(https);
                                if (result.Result.ResponseStatus.IsSuccess)
                                {
                                    LogHelper.WriteCloudLog("撤销-" + TypeNeeds.Type, Convert.ToInt32(result.Result.ResponseStatus.SuccessEntitys[0].Id), result.Result.ResponseStatus.SuccessEntitys[0].Number, 1, "中合写入金蝶", Contout, https, "");
                                    NeedsResult needs = new NeedsResult();
                                    needs.Id = result.Result.ResponseStatus.SuccessEntitys[0].Id;
                                    needs.Number = result.Result.ResponseStatus.SuccessEntitys[0].Number;

                                    ConsoleWrite("A", TypeNeeds.Type + "-CancelAssign:", JsonConvert.SerializeObject(needs));
                                    isSuccess.Code = 0;
                                    isSuccess.Result = needs;
                                    isSuccess.Message = null;
                                }
                                else
                                {
                                    LogHelper.WriteCloudLog("撤销-" + TypeNeeds.Type, 0, "", 0, "中合写入金蝶", Contout, https, "");
                                    ConsoleWrite("B", TypeNeeds.Type + "-CancelAssign:", JsonConvert.SerializeObject(result.Result.ResponseStatus.Errors[0].Message));
                                    isSuccess.Code = 500;
                                    isSuccess.Result = null;
                                    isSuccess.Message = result.Result.ResponseStatus.Errors[0].Message;
                                    return JsonConvert.SerializeObject(isSuccess);
                                }
                                break;
                            case "UnAudit"://反审核
                                https = InvokeHelper.UnAudit(TypeNeeds.Type, Contout);
                                result = JsonConvert.DeserializeObject<FResult>(https);
                                if (result.Result.ResponseStatus.IsSuccess)
                                {
                                    LogHelper.WriteCloudLog("反审核-" + TypeNeeds.Type, Convert.ToInt32(result.Result.ResponseStatus.SuccessEntitys[0].Id), result.Result.ResponseStatus.SuccessEntitys[0].Number, 1, "中合写入金蝶", Contout, https, "");
                                    NeedsResult needs = new NeedsResult();
                                    needs.Id = result.Result.ResponseStatus.SuccessEntitys[0].Id;
                                    needs.Number = result.Result.ResponseStatus.SuccessEntitys[0].Number;

                                    ConsoleWrite("A", TypeNeeds.Type + "-UnAudit:", JsonConvert.SerializeObject(needs));
                                    isSuccess.Code = 0;
                                    isSuccess.Result = needs;
                                    isSuccess.Message = null;
                                }
                                else
                                {
                                    LogHelper.WriteCloudLog("反审核-" + TypeNeeds.Type, 0, "", 0, "中合写入金蝶", Contout, https, "");
                                    ConsoleWrite("B", TypeNeeds.Type + "-UnAudit:", JsonConvert.SerializeObject(result.Result.ResponseStatus.Errors[0].Message));
                                    isSuccess.Code = 500;
                                    isSuccess.Result = null;
                                    isSuccess.Message = result.Result.ResponseStatus.Errors[0].Message;
                                    return JsonConvert.SerializeObject(isSuccess);
                                }
                                break;
                            case "Delete"://删除
                                https = InvokeHelper.Delete(TypeNeeds.Type, Contout);
                                result = JsonConvert.DeserializeObject<FResult>(https);
                                if (result.Result.ResponseStatus.IsSuccess)
                                {
                                    LogHelper.WriteCloudLog("删除-" + TypeNeeds.Type, Convert.ToInt32(result.Result.ResponseStatus.SuccessEntitys[0].Id), result.Result.ResponseStatus.SuccessEntitys[0].Number, 1, "中合写入金蝶", Contout, https, "");
                                    NeedsResult needs = new NeedsResult();
                                    needs.Id = result.Result.ResponseStatus.SuccessEntitys[0].Id;
                                    needs.Number = result.Result.ResponseStatus.SuccessEntitys[0].Number;

                                    ConsoleWrite("A", TypeNeeds.Type + "-Delete:", JsonConvert.SerializeObject(needs));
                                    isSuccess.Code = 0;
                                    isSuccess.Result = needs;
                                    isSuccess.Message = null;
                                }
                                else
                                {
                                    LogHelper.WriteCloudLog("删除-" + TypeNeeds.Type, 0, "", 0, "中合写入金蝶", Contout, https, "");
                                    ConsoleWrite("B", TypeNeeds.Type + "-Delete:", JsonConvert.SerializeObject(result.Result.ResponseStatus.Errors[0].Message));
                                    isSuccess.Code = 500;
                                    isSuccess.Result = null;
                                    isSuccess.Message = result.Result.ResponseStatus.Errors[0].Message;
                                    return JsonConvert.SerializeObject(isSuccess);
                                }
                                break;
                            case "Cancel"://作废
                                https = InvokeHelper.ExcuteOperation(TypeNeeds.Type, "Cancel", Contout);
                                result = JsonConvert.DeserializeObject<FResult>(https);
                                if (result.Result.ResponseStatus.IsSuccess)
                                {
                                    LogHelper.WriteCloudLog("作废-" + TypeNeeds.Type, Convert.ToInt32(result.Result.ResponseStatus.SuccessEntitys[0].Id), result.Result.ResponseStatus.SuccessEntitys[0].Number, 1, "中合写入金蝶", Contout, https, "");
                                    NeedsResult needs = new NeedsResult();
                                    needs.Id = result.Result.ResponseStatus.SuccessEntitys[0].Id;
                                    needs.Number = result.Result.ResponseStatus.SuccessEntitys[0].Number;

                                    ConsoleWrite("A", TypeNeeds.Type + "-ExcuteOperation:", JsonConvert.SerializeObject(needs));
                                    isSuccess.Code = 0;
                                    isSuccess.Result = needs;
                                    isSuccess.Message = null;
                                }
                                else
                                {
                                    LogHelper.WriteCloudLog("作废-" + TypeNeeds.Type, 0, "", 0, "中合写入金蝶", Contout, https, "");
                                    ConsoleWrite("B", TypeNeeds.Type + "-ExcuteOperation:", JsonConvert.SerializeObject(result.Result.ResponseStatus.Errors[0].Message));
                                    isSuccess.Code = 500;
                                    isSuccess.Result = null;
                                    isSuccess.Message = result.Result.ResponseStatus.Errors[0].Message;
                                    return JsonConvert.SerializeObject(isSuccess);
                                }
                                break;
                            case "UnCancel"://反作废
                                https = InvokeHelper.ExcuteOperation(TypeNeeds.Type, "Uncancel", Contout);
                                result = JsonConvert.DeserializeObject<FResult>(https);
                                if (result.Result.ResponseStatus.IsSuccess)
                                {
                                    LogHelper.WriteCloudLog("反作废-" + TypeNeeds.Type, Convert.ToInt32(result.Result.ResponseStatus.SuccessEntitys[0].Id), result.Result.ResponseStatus.SuccessEntitys[0].Number, 1, "中合写入金蝶", Contout, https, "");
                                    NeedsResult needs = new NeedsResult();
                                    needs.Id = result.Result.ResponseStatus.SuccessEntitys[0].Id;
                                    needs.Number = result.Result.ResponseStatus.SuccessEntitys[0].Number;

                                    ConsoleWrite("A", TypeNeeds.Type + "-ExcuteOperation:", JsonConvert.SerializeObject(needs));
                                    isSuccess.Code = 0;
                                    isSuccess.Result = needs;
                                    isSuccess.Message = null;
                                }
                                else
                                {
                                    LogHelper.WriteCloudLog("反作废-" + TypeNeeds.Type, 0, "", 0, "中合写入金蝶", Contout, https, "");
                                    ConsoleWrite("B", TypeNeeds.Type + "-ExcuteOperation:", JsonConvert.SerializeObject(result.Result.ResponseStatus.Errors[0].Message));
                                    isSuccess.Code = 500;
                                    isSuccess.Result = null;
                                    isSuccess.Message = result.Result.ResponseStatus.Errors[0].Message;
                                    return JsonConvert.SerializeObject(isSuccess);
                                }
                                break;
                            default:
                                ConsoleWrite("B", TypeNeeds.Type + "-CloudUnaDe:", "请输入有效操做类型！！！");
                                isSuccess.Code = 500;
                                isSuccess.Result = null;
                                isSuccess.Message = "第" + (i + 1) + "个操作类型无效，请输入有效操做类型！！！";
                                break;
                        }
                    }
                    return JsonConvert.SerializeObject(isSuccess);
                }
                else
                {
                    ConsoleWrite("B", TypeNeeds.Type + "-Login:", LoginMessage);
                    isSuccess.Code = 500;
                    isSuccess.Result = null;
                    isSuccess.Message = LoginMessage;
                    return JsonConvert.SerializeObject(isSuccess);
                }

            }
            catch (Exception e)
            {
                ConsoleWrite("C", "CloudDocumentOp方法异常信息:", e.Message);
                LogHelper.WriteCloudLog(TypeNeeds.Type + "调用-CloudDocumentOp", 0, "", 0, "中合写入金蝶", "", "", e.Message);

                isSuccess.Code = 505;
                isSuccess.Result = null;
                isSuccess.Message = "登录失败！";
                return JsonConvert.SerializeObject(isSuccess);
            }
        }


        /// <summary>
        /// 写入金蝶-客户
        /// </summary>
        /// <param name="_RootQuery"></param>
        /// <returns></returns>
        [Route("CloudCustSave"), HttpPost]
        public string Kingdee_CustomerSave(Crm_RootQuery<Crm_AccountsQuery> _RootQuery)
        {
            IsSuccessResult isSuccess = new IsSuccessResult();
            BD_CustomerBus _CustomerBus = new BD_CustomerBus();
            try
            {
                if (_RootQuery == null || _RootQuery.result.Count <= 0)
                {
                    ConsoleWrite("B", "Kingdee_CustomerSave：", "Json为空！");
                    isSuccess.Code = 200;
                    isSuccess.Result = null;
                    isSuccess.Message = "请传入客户信息！";
                    return JsonConvert.SerializeObject(isSuccess);
                }
                var LoginResult = InvokeHelper.Login();
                TxtHelper.LogWrite("Kingdee_CustomerSave-登录返回：" + LoginResult);
                var isLogin = JObject.Parse(LoginResult)["LoginResultType"].Value<int>();
                var LoginMessage = JObject.Parse(LoginResult)["Message"].Value<string>();
                if (isLogin == 1)
                {
                    foreach (Crm_AccountsQuery item in _RootQuery.result)
                    {
                        string JsonTest = _CustomerBus.Get_CustomerData(item);
                        string https = InvokeHelper.Save("BD_Customer", JsonTest);
                        FResult result = JsonConvert.DeserializeObject<FResult>(https);
                        if (result.Result.ResponseStatus.IsSuccess)
                        {
                            ConsoleWrite("A", "Kingdee_CustomerSave-Save:", "Success");
                            LogHelper.WriteCloudLog("保存-客户", Convert.ToInt32(result.Result.ResponseStatus.SuccessEntitys[0].Id), result.Result.ResponseStatus.SuccessEntitys[0].Number, 1, "灵当写入金蝶", JsonTest, https, "");
                            NeedsResult needs = new NeedsResult();
                            needs.Id = Convert.ToInt32(result.Result.ResponseStatus.SuccessEntitys[0].Id);
                            needs.Number = result.Result.ResponseStatus.SuccessEntitys[0].Number;
                            isSuccess.Code = 0;
                            isSuccess.Result = needs;
                            isSuccess.Message = null;
                        }
                        else
                        {
                            ConsoleWrite("B", "Kingdee_CustomerSave-Save:", result.Result.ResponseStatus.Errors[0].Message);
                            LogHelper.WriteCloudLog("保存-客户", 0, "", 0, "灵当写入金蝶", JsonTest, https, "");
                            isSuccess.Code = 0;
                            isSuccess.Result = null;
                            isSuccess.Message = result.Result.ResponseStatus.Errors[0].Message;
                        }
                    }
                    return JsonConvert.SerializeObject(isSuccess);
                }
                else
                {
                    ConsoleWrite("B", "Kingdee_CustomerSave-Login:", LoginMessage);
                    isSuccess.Code = 500;
                    isSuccess.Result = null;
                    isSuccess.Message = LoginMessage;
                    return JsonConvert.SerializeObject(isSuccess);
                }
            }
            catch (Exception e)
            {
                LogHelper.WriteCloudLog("保存-客户", 0, "", 0, "灵当写入金蝶", "", "", e.Message);
                ConsoleWrite("C", "Kingdee_CustomerSave：", e.Message);

                isSuccess.Code = 505;
                isSuccess.Result = null;
                isSuccess.Message = "登录失败！";
                return JsonConvert.SerializeObject(isSuccess);
            }

        }


        /// <summary>
        /// 查询金蝶库存
        /// </summary>
        /// <param name="MaterialNo"></param>
        /// <returns></returns>
        [Route("CloudQuery"), HttpPost]
        public string Kingdee_Query(DataType<List<OrgBase>> MaterialNo)
        {
            IsSuccessResult isSuccess = new IsSuccessResult();
            try
            {
                if (MaterialNo == null)
                {
                    isSuccess.Code = 500;
                    isSuccess.Result = null;
                    isSuccess.Message = "请传入正确的json！！";
                    return JsonConvert.SerializeObject(isSuccess);
                }
                if (string.IsNullOrEmpty(MaterialNo.Type))
                {
                    isSuccess.Code = 500;
                    isSuccess.Result = null;
                    isSuccess.Message = "组织编码不可为空！";
                    return JsonConvert.SerializeObject(isSuccess);
                }
                if (MaterialNo.Data.Count <= 0 || MaterialNo.Data == null)
                {
                    isSuccess.Code = 500;
                    isSuccess.Result = null;
                    isSuccess.Message = "物料编码不可为空！";
                    return JsonConvert.SerializeObject(isSuccess);
                }

                SAL_StockQueryBus _StockQueryBus = new SAL_StockQueryBus();
                string SQLWhere = "";
                string Materiml = "";

                string index = "";
                int idx = 0;
                foreach (OrgBase item in MaterialNo.Data)
                {
                    if (SQLWhere.IndexOf("''" + item.FNumber + "''") != -1)
                    {
                        if (string.IsNullOrEmpty(index))
                        {
                            index = idx.ToString();
                        }
                        else
                        {
                            index = index + "," + idx.ToString();
                        }
                        idx++;
                        continue;
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(SQLWhere))
                        {
                            SQLWhere = "''" + item.FNumber + "''";
                        }
                        else
                        {
                            SQLWhere = SQLWhere + ",''" + item.FNumber + "''";
                        }
                        idx++;
                    }

                }
                string sql = string.Format($"exec Get_OutAndInStockQtyData '{MaterialNo.Type}','{SQLWhere}'");
                DataTable data = DBHelper.ExecuteQuery(sql);

                NeedsQty queries = new NeedsQty();
                queries.DataOp = "Select";

                queries.Data = new List<NeedsQuery>();
                NeedsQuery needs = new NeedsQuery();
                foreach (DataRow items in data.Rows)
                {
                    decimal RealQty = Convert.ToDecimal(items["FINVLEFTBASEQTY"]);
                    decimal LockLibraryQty = Convert.ToDecimal(items["FLOCKBASEQTY"]);
                    decimal ExpectedQty = Convert.ToDecimal(items["FAWAITINBASEQTY"]);
                    decimal PreRecordedQTY = Convert.ToDecimal(items["FAWAITOUTBASEQTY"]);
                    decimal ExpectedToBeAvailableQty = Convert.ToDecimal(items["FAVBBASEQTY"]);
                    if (items["FMATERIALNUMBER"].ToString() == Materiml)
                    {
                        DetailEntry entry = new DetailEntry();
                        entry.StockName = items["FSTOCKNAME"].ToString();
                        entry.RealQty = RealQty;
                        entry.LockLibraryQty = LockLibraryQty;
                        entry.ExpectedQty = ExpectedQty;
                        entry.PreRecordedQTY = PreRecordedQTY;
                        entry.ExpectedToBeAvailableQty = ExpectedToBeAvailableQty;
                        needs.Detail.Add(entry);

                        needs.RealQty = needs.RealQty + RealQty;
                        needs.LockLibraryQty = needs.LockLibraryQty + LockLibraryQty;
                        needs.ExpectedQty = needs.ExpectedQty + ExpectedQty;
                        needs.PreRecordedQTY = needs.PreRecordedQTY + PreRecordedQTY;
                        needs.ExpectedToBeAvailableQty = needs.ExpectedToBeAvailableQty + ExpectedToBeAvailableQty;
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(Materiml))
                        {
                            queries.Data.Add(needs);
                        }
                        needs = new NeedsQuery();
                        needs.Number = items["FMATERIALNUMBER"].ToString();
                        needs.RealQty = 0;
                        needs.LockLibraryQty = 0;
                        needs.ExpectedQty = 0;
                        needs.PreRecordedQTY = 0;
                        needs.ExpectedToBeAvailableQty = 0;

                        needs.Detail = new List<DetailEntry>();
                        DetailEntry entry = new DetailEntry();
                        entry.StockName = items["FSTOCKNAME"].ToString();
                        entry.RealQty = RealQty;
                        entry.LockLibraryQty = LockLibraryQty;
                        entry.ExpectedQty = ExpectedQty;
                        entry.PreRecordedQTY = PreRecordedQTY;
                        entry.ExpectedToBeAvailableQty = ExpectedToBeAvailableQty;
                        needs.Detail.Add(entry);

                        needs.RealQty = needs.RealQty + RealQty;
                        needs.LockLibraryQty = needs.LockLibraryQty + LockLibraryQty;
                        needs.ExpectedQty = needs.ExpectedQty + ExpectedQty;
                        needs.PreRecordedQTY = needs.PreRecordedQTY + PreRecordedQTY;
                        needs.ExpectedToBeAvailableQty = needs.ExpectedToBeAvailableQty + ExpectedToBeAvailableQty;
                    }
                    Materiml = items["FMATERIALNUMBER"].ToString();
                }
                if (data.Rows.Count > 0)
                {
                    queries.Data.Add(needs);
                }

                //去重
                if (!string.IsNullOrWhiteSpace(index))
                {
                    var ArriIdx = index.Split(',');
                    int IdxInt = 0;
                    foreach (string item in ArriIdx)
                    {
                        MaterialNo.Data.RemoveAt((Convert.ToInt32(item) - IdxInt));
                        IdxInt++;
                    }
                }


                //金蝶没有库存的物料
                int DataCount = (MaterialNo.Data.Count - queries.Data.Count);
                for (int i = 0; i < MaterialNo.Data.Count;)
                {
                    if (DataCount == MaterialNo.Data.Count)
                    {
                        break;
                    }
                    for (int x = 0; x < data.Rows.Count; x++)
                    {
                        if (data.Rows[x]["FMATERIALNUMBER"].ToString() == MaterialNo.Data[i].FNumber)
                        {
                            MaterialNo.Data.RemoveAt(i);
                            break;
                        }
                        else if ((x + 1) == data.Rows.Count)
                        {
                            i++;
                        }
                    }
                }

                foreach (OrgBase itemb in MaterialNo.Data)
                {
                    needs = new NeedsQuery();
                    needs.Number = itemb.FNumber;
                    needs.RealQty = 0;
                    needs.LockLibraryQty = 0;
                    needs.ExpectedQty = 0;
                    needs.PreRecordedQTY = 0;
                    needs.ExpectedToBeAvailableQty = 0;

                    needs.Detail = new List<DetailEntry>();
                    DetailEntry entry = new DetailEntry();
                    entry.StockName = null;
                    entry.RealQty = 0;
                    entry.LockLibraryQty = 0;
                    entry.ExpectedQty = 0;
                    entry.PreRecordedQTY = 0;
                    entry.ExpectedToBeAvailableQty = 0;
                    needs.Detail.Add(entry);
                    queries.Data.Add(needs);
                }

                queries.DataRows = queries.Data.Count;

                isSuccess.Result = queries;
                return JsonConvert.SerializeObject(isSuccess);
            }
            catch (Exception e)
            {
                ConsoleWrite("C", "Kingdee_Query方法异常信息:", e.Message);

                LogHelper.WriteCloudLog("Kingdee_Query", 0, "", 0, "灵当查询金蝶", "", "", e.Message);

                isSuccess.Code = 505;
                isSuccess.Result = null;
                isSuccess.Message = "登录失败！";
                return JsonConvert.SerializeObject(isSuccess);
            }
        }


        /// <summary>
        /// 查询金蝶是否有库存存在
        /// </summary>
        /// <param name="MaterialNo"></param>
        /// <returns></returns>
        [Route("CloudInOutStock"), HttpPost]
        public string Kingdee_StockQuery(DataType<List<OrgBase>> MaterialNo)
        {
            IsSuccessResult isSuccess = new IsSuccessResult();
            try
            {
                if (MaterialNo == null)
                {
                    isSuccess.Code = 500;
                    isSuccess.Result = null;
                    isSuccess.Message = "请传入正确的json！！";
                    return JsonConvert.SerializeObject(isSuccess);
                }
                if (string.IsNullOrEmpty(MaterialNo.Type))
                {
                    isSuccess.Code = 500;
                    isSuccess.Result = null;
                    isSuccess.Message = "组织编码不可为空！";
                    return JsonConvert.SerializeObject(isSuccess);
                }
                if (MaterialNo.Data.Count <= 0 || MaterialNo.Data == null)
                {
                    isSuccess.Code = 500;
                    isSuccess.Result = null;
                    isSuccess.Message = "物料编码不可为空！";
                    return JsonConvert.SerializeObject(isSuccess);
                }

                string SQLWhere = "";
                string index = "";
                int idx = 0;
                foreach (OrgBase item in MaterialNo.Data)
                {
                    if (SQLWhere.IndexOf("''" + item.FNumber + "''") != -1)
                    {
                        if (string.IsNullOrEmpty(index))
                        {
                            index = idx.ToString();
                        }
                        else
                        {
                            index = index + "," + idx.ToString();
                        }
                        idx++;
                        continue;
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(SQLWhere))
                        {
                            SQLWhere = "''" + item.FNumber + "''";
                        }
                        else
                        {
                            SQLWhere = SQLWhere + ",''" + item.FNumber + "''";
                        }
                        idx++;
                    }

                }

                string sql = string.Format($"exec Get_OutAndInStockQtyData '{MaterialNo.Type}','{SQLWhere}'");
                DataTable data = DBHelper.ExecuteQuery(sql);

                NeedsInOut inOut = new NeedsInOut();
                inOut.OpType = "Select";
                inOut.DataEntry = new List<NeedsInOutEntry>();


                string Materiml = "";


                NeedsQuery needs = new NeedsQuery();
                foreach (DataRow items in data.Rows)
                {
                    decimal RealQty = Convert.ToDecimal(items["FINVLEFTBASEQTY"]);
                    decimal LockLibraryQty = Convert.ToDecimal(items["FLOCKBASEQTY"]);
                    decimal ExpectedQty = Convert.ToDecimal(items["FAWAITINBASEQTY"]);
                    decimal PreRecordedQTY = Convert.ToDecimal(items["FAWAITOUTBASEQTY"]);
                    decimal ExpectedToBeAvailableQty = Convert.ToDecimal(items["FAVBBASEQTY"]);
                    if (items["FMATERIALNUMBER"].ToString() == Materiml)
                    {
                        DetailEntry entry = new DetailEntry();
                        entry.StockName = items["FSTOCKNAME"].ToString();
                        entry.RealQty = RealQty;
                        entry.LockLibraryQty = LockLibraryQty;
                        entry.ExpectedQty = ExpectedQty;
                        entry.PreRecordedQTY = PreRecordedQTY;
                        entry.ExpectedToBeAvailableQty = ExpectedToBeAvailableQty;
                        needs.Detail.Add(entry);

                        needs.RealQty = needs.RealQty + RealQty;
                        needs.LockLibraryQty = needs.LockLibraryQty + LockLibraryQty;
                        needs.ExpectedQty = needs.ExpectedQty + ExpectedQty;
                        needs.PreRecordedQTY = needs.PreRecordedQTY + PreRecordedQTY;
                        needs.ExpectedToBeAvailableQty = needs.ExpectedToBeAvailableQty + ExpectedToBeAvailableQty;
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(Materiml))
                        {
                            NeedsInOutEntry inOutEntry = new NeedsInOutEntry();
                            inOutEntry.MaterimalNo = needs.Number;
                            inOutEntry.StockQty = needs.ExpectedToBeAvailableQty;
                            if (needs.ExpectedToBeAvailableQty > 0)
                            {
                                inOutEntry.IsInOutStock = true;
                            }
                            if (needs.ExpectedToBeAvailableQty <= 0)
                            {
                                inOutEntry.IsInOutStock = false;
                            }
                            inOut.DataEntry.Add(inOutEntry);
                        }
                        needs = new NeedsQuery();
                        needs.Number = items["FMATERIALNUMBER"].ToString();
                        needs.RealQty = 0;
                        needs.LockLibraryQty = 0;
                        needs.ExpectedQty = 0;
                        needs.PreRecordedQTY = 0;
                        needs.ExpectedToBeAvailableQty = 0;

                        needs.Detail = new List<DetailEntry>();
                        DetailEntry entry = new DetailEntry();
                        entry.StockName = items["FSTOCKNAME"].ToString();
                        entry.RealQty = RealQty;
                        entry.LockLibraryQty = LockLibraryQty;
                        entry.ExpectedQty = ExpectedQty;
                        entry.PreRecordedQTY = PreRecordedQTY;
                        entry.ExpectedToBeAvailableQty = ExpectedToBeAvailableQty;
                        needs.Detail.Add(entry);

                        needs.RealQty = needs.RealQty + RealQty;
                        needs.LockLibraryQty = needs.LockLibraryQty + LockLibraryQty;
                        needs.ExpectedQty = needs.ExpectedQty + ExpectedQty;
                        needs.PreRecordedQTY = needs.PreRecordedQTY + PreRecordedQTY;
                        needs.ExpectedToBeAvailableQty = needs.ExpectedToBeAvailableQty + ExpectedToBeAvailableQty;
                    }
                    Materiml = items["FMATERIALNUMBER"].ToString();
                }

                if (data.Rows.Count > 0)
                {
                    NeedsInOutEntry inOutEntry = new NeedsInOutEntry();
                    inOutEntry.MaterimalNo = needs.Number;
                    inOutEntry.StockQty = needs.ExpectedToBeAvailableQty;
                    if (needs.ExpectedToBeAvailableQty > 0)
                    {
                        inOutEntry.IsInOutStock = true;
                    }
                    if (needs.ExpectedToBeAvailableQty <= 0)
                    {
                        inOutEntry.IsInOutStock = false;
                    }
                    inOut.DataEntry.Add(inOutEntry);
                }

                //去重
                if (!string.IsNullOrWhiteSpace(index))
                {
                    var ArriIdx = index.Split(',');
                    int IdxInt = 0;
                    foreach (string item in ArriIdx)
                    {
                        MaterialNo.Data.RemoveAt((Convert.ToInt32(item) - IdxInt));
                        IdxInt++;
                    }
                }


                //金蝶没有库存的物料
                int DataCount = (MaterialNo.Data.Count - data.Rows.Count);
                for (int i = 0; i < MaterialNo.Data.Count;)
                {
                    if (DataCount == MaterialNo.Data.Count)
                    {
                        break;
                    }
                    for (int x = 0; x < data.Rows.Count; x++)
                    {
                        if (data.Rows[x]["FMATERIALNUMBER"].ToString() == MaterialNo.Data[i].FNumber)
                        {
                            MaterialNo.Data.RemoveAt(i);
                            break;
                        }
                        else if ((x + 1) == data.Rows.Count)
                        {
                            i++;
                        }
                    }
                }

                foreach (OrgBase itemb in MaterialNo.Data)
                {
                    NeedsInOutEntry inOutEntry = new NeedsInOutEntry();
                    inOutEntry.MaterimalNo = itemb.FNumber;
                    inOutEntry.StockQty = 0;
                    inOutEntry.IsInOutStock = false;
                    inOut.DataEntry.Add(inOutEntry);
                }
                inOut.DataRows = inOut.DataEntry.Count;

                isSuccess.Code = 0;
                isSuccess.Result = inOut;
                isSuccess.Message = null;
                return JsonConvert.SerializeObject(isSuccess);
            }
            catch (Exception ex)
            {
                isSuccess.Code = 505;
                isSuccess.Result = null;
                isSuccess.Message = ex.Message;
                return JsonConvert.SerializeObject(isSuccess);
            }
        }
        #endregion


        #region 2.灵当相关业务


        /// <summary>
        /// 写入灵当CRM 物料
        /// </summary>
        /// <param name="Type"></param>
        /// <param name="Data"></param>
        /// <returns></returns>
        [Route("Set_CrmMaterApi"), HttpPost]
        public async Task<string> Set_CrmMaterApi(Crm_MaterialList Data)
        {
            Get_Crm_Material _Crm_Material = new Get_Crm_Material();
            IsSuccessResult isSuccess = new IsSuccessResult();
            Crm_Result _Result = new Crm_Result();
            string WriteType = "";
            string _Materials = "";
            if (Data == null)
            {
                isSuccess.Code = 506;
                isSuccess.Result = null;
                isSuccess.Message = "数据不可为空！";
                return JsonConvert.SerializeObject(isSuccess);
            }
            try
            {
                string httprs = await WebHelper.HttpPost(CrmUrl + "/crmapi/apiKey.php?authen_code=" + Crmcode, null, null, "multipart/form-data");
                CrmApiKey crmApi = JsonConvert.DeserializeObject<CrmApiKey>(httprs);
                if (crmApi.code == "success")
                {
                    Crm_MaterialList _Data = Data;
                    _Materials = _Crm_Material.MaterialResult(crmApi.key, crmApi.token, _Data);
                    WriteType = "物料";
                    httprs = await WebHelper.HttpPost(CrmUrl + "/crmapi/api_crmoperation.php", _Materials, null, "multipart/form-data");
                    isSuccess = _Result.Crm_SaveResult("Products", httprs, _Materials);
                    if (isSuccess.Code == 0)
                    {
                        ConsoleWrite("A", WriteType + "_Save:", httprs);
                        return JsonConvert.SerializeObject(isSuccess);
                    }
                    else
                    {
                        ConsoleWrite("B", WriteType + "_Save:", httprs);
                        return JsonConvert.SerializeObject(isSuccess);
                    }
                }
                else
                {
                    ConsoleWrite("B", "SetMaterial_Login:", httprs);
                    isSuccess.Code = 200;
                    isSuccess.Result = null;
                    isSuccess.Message = httprs;
                    return JsonConvert.SerializeObject(isSuccess);
                }
            }
            catch (Exception e)
            {
                ConsoleWrite("C", "SetMaterial:", e.Message);

                LogHelper.WriteLog(WriteType + "异常", 0, "", 0, "金蝶写入商城", e.Message, "", e.Message, "6440d3ae40a972");

                isSuccess.Code = 505;
                isSuccess.Result = null;
                isSuccess.Message = "灵当：登录失败！！";
                return JsonConvert.SerializeObject(isSuccess);
            }
        }

        /// <summary>
        /// 写入灵当Crm 客户
        /// </summary>
        /// <param name="Data"></param>
        /// <returns></returns>
        [Route("Set_CrmCustomerApi"), HttpPost]
        public async Task<string> Set_CrmCustomerApi(Crm_Accounts Data)
        {
            Get_Crm_Material _Crm_Material = new Get_Crm_Material();
            IsSuccessResult isSuccess = new IsSuccessResult();
            Crm_Result _Result = new Crm_Result();
            string _Materials = "";
            string WriteType = "";
            if (Data == null)
            {
                isSuccess.Code = 506;
                isSuccess.Result = null;
                isSuccess.Message = "数据不可为空！";
                return JsonConvert.SerializeObject(isSuccess);
            }
            try
            {
                string httprs = await WebHelper.HttpPost(CrmUrl + "/crmapi/apiKey.php?authen_code=" + Crmcode, null, null, "multipart/form-data");
                CrmApiKey crmApi = JsonConvert.DeserializeObject<CrmApiKey>(httprs);
                if (crmApi.code == "success")
                {
                    Crm_Accounts _Account = Data;
                    _Materials = _Crm_Material.AccountsResult(crmApi.key, crmApi.token, _Account);
                    WriteType = "客户";
                    httprs = await WebHelper.HttpPost(CrmUrl + "/crmapi/api_crmoperation.php", _Materials, null, "multipart/form-data");
                    isSuccess = _Result.Crm_SaveResult("Accounts", httprs, _Materials);
                    if (isSuccess.Code == 0)
                    {
                        ConsoleWrite("A", WriteType + "_Save:", httprs);
                        return JsonConvert.SerializeObject(isSuccess);
                    }
                    else
                    {
                        ConsoleWrite("B", WriteType + "_Save:", httprs);
                        return JsonConvert.SerializeObject(isSuccess);
                    }
                }
                else
                {
                    ConsoleWrite("B", "SetMaterial_Login:", httprs);
                    isSuccess.Code = 200;
                    isSuccess.Result = null;
                    isSuccess.Message = httprs;
                    return JsonConvert.SerializeObject(isSuccess);
                }
            }
            catch (Exception e)
            {
                ConsoleWrite("C", "SetMaterial:", e.Message);

                LogHelper.WriteLog(WriteType + "异常", 0, "", 0, "金蝶写入商城", e.Message, "", e.Message, "6440d3ae40a972");

                isSuccess.Code = 505;
                isSuccess.Result = null;
                isSuccess.Message = "登录失败！！";
                return JsonConvert.SerializeObject(isSuccess);
            }
        }


        /// <summary>
        /// 查询灵当数据
        /// </summary>
        /// <returns></returns>
        [Route("CrmCustomerQuery"), HttpPost]
        public async Task<string> Get_CustomerQuery(Crm_QueryWhere Type)
        {
            //Crm_RootQuery<Crm_AccountsQuery> _RootQuery = new Crm_RootQuery<Crm_AccountsQuery>();
            string TypeName = "";
            Crm_SAL_Order SALData = new Crm_SAL_Order();
            switch (Type.ModelType)
            {
                case "Accounts":
                    TypeName = "客户";
                    break;
                case "SalesOrder":
                    TypeName = "销售订单";
                    break;
                case "CashBill":
                    TypeName = "收款单";
                    break;
                case "Quotes":
                    TypeName = "收款单";
                    break;
                default:
                    return "请输入有效类型";
                    break;
            }
            try
            {
                string httprs = await WebHelper.HttpPost(CrmUrl + "/crmapi/apiKey.php?authen_code=" + Crmcode, null, null, "multipart/form-data");
                CrmApiKey crmApi = JsonConvert.DeserializeObject<CrmApiKey>(httprs);
                if (crmApi.code == "success")
                {
                    Crm_QueryBus _QueryBus = new Crm_QueryBus();
                    string JsonTest = _QueryBus.Get_CRM_Query(Type.ModelType, crmApi.key, crmApi.token, Type.PageSize, Type.PageNum, Type.crmWheres);
                    httprs = await WebHelper.HttpPost32(CrmUrl + "/crmapi/crmoperation.php", JsonTest, null, "application/json");
                    //var _RootQuery = JsonConvert.DeserializeObject<Crm_RootQuery<Crm_AccountsQuery>>(httprs);

                    LogHelper.WriteLog("灵当-查询" + TypeName, 0, "", 1, "查询灵当", JsonTest, httprs, "", "");
                    ConsoleWrite("A", TypeName + "_Query:", httprs);
                    return httprs;
                }
                else
                {
                    LogHelper.WriteLog("灵当-查询" + TypeName, 0, "", 0, "查询灵当", "", httprs, "", "");
                    ConsoleWrite("B", TypeName + "_Query:", httprs);
                    return httprs;
                }
            }
            catch (Exception e)
            {
                ConsoleWrite("C", TypeName + "_Query:", e.Message);
                LogHelper.WriteLog("Get_CustomerQuery异常", 0, "", 0, "金蝶写入商城", e.Message, "", e.Message, "");
                return "登录失败！";
            }
        }

        private readonly static object _lockSales = new object();

        private readonly static object _lockQuota = new object();

        [Route("CrmSalesQuery"), HttpPost]
        public string Get_SalestionQuery(NeedsNumbers data)
        {
            lock (_lockSales)
            {
                string Jsons = string.Empty;
                Crm_QueryBus _QueryBus = new Crm_QueryBus();
                DataSet ds = new DataSet();
                IsSuccessResult result = new IsSuccessResult();
                List<Crm_MySqlSalesQuery> MSQuery = new List<Crm_MySqlSalesQuery>();
                try
                {
                    if (data == null)
                    {
                        result.Code = 500;
                        result.Result = "";
                        result.Message = "请传入正确参数！";
                    }
                    else if (string.IsNullOrWhiteSpace(data.Number))
                    {
                        result.Code = 505;
                        result.Result = "";
                        result.Message = "请传入需要查询的单号！";
                    }
                    else
                    {
                        ConsoleWrite("A", "查询灵当（报价单）:", "传入（" + JsonConvert.SerializeObject(data) + "）");

                        string sql = _QueryBus.Get_Crm_MySqlQueryStateMent("SaleOrder", data);

                        try
                        {
                            ds = Common.MYSQLHelper.Query_New(sql, "");
                            if (ds != null && ds.Tables[0].Rows.Count > 0)
                            {
                                if (ds != null && ds.Tables[0].Rows.Count > 0)
                                {
                                    foreach (DataRow item in ds.Tables[0].Rows)
                                    {
                                        Crm_MySqlSalesQuery _MSDataQuery = new Crm_MySqlSalesQuery();
                                        _MSDataQuery.Quota_no = item["报价单号"].ToString();
                                        _MSDataQuery.ApprovalStatus = item["审批状态"].ToString();
                                        _MSDataQuery.QuotaType = item["报价单类型"].ToString();
                                        _MSDataQuery.PackageName = item["套餐名"].ToString();
                                        _MSDataQuery.CustName = item["客户名称"].ToString();
                                        _MSDataQuery.SalesStaff = item["销售负责人"].ToString();
                                        _MSDataQuery.OrderRate = item["订单折扣率"].ToString();
                                        _MSDataQuery.Amount = item["合计"].ToString();
                                        MSQuery.Add(_MSDataQuery);
                                    }
                                }
                                result.Code = 0;
                                result.Result = JsonConvert.SerializeObject(MSQuery);
                                result.Message = "";
                            }
                            else
                            {
                                result.Code = 501;
                                result.Result = "";
                                result.Message = "查无数据！";
                            }
                            ConsoleWrite("A", "查询灵当:", "返回（" + JsonConvert.SerializeObject(MSQuery) + "）");
                        }
                        catch (Exception ex)
                        {
                            result.Code = 506;
                            result.Result = "";
                            result.Message = ex.Message;
                        }
                    }

                    return JsonConvert.SerializeObject(result);

                }
                catch (Exception ex)
                {
                    ConsoleWrite("A", "查询灵当:", ex.Message);
                    result.Code = 506;
                    result.Result = "";
                    result.Message = ex.Message;
                    return JsonConvert.SerializeObject(result);
                }
            }
        }

        [Route("CrmQuotaQuery"), HttpPost]
        public string Get_QuotationQuery(NeedsNumbers data)
        {
            lock (_lockQuota)
            {
                string Jsons = string.Empty;
                Crm_QueryBus _QueryBus = new Crm_QueryBus();
                DataSet ds = new DataSet();
                IsSuccessResult result = new IsSuccessResult();
                List<Crm_MySqlQuotaQuery> MSQuery = new List<Crm_MySqlQuotaQuery>();
                try
                {
                    if (data == null)
                    {
                        result.Code = 500;
                        result.Result = "";
                        result.Message = "请传入正确参数！";
                    }
                    else if (string.IsNullOrWhiteSpace(data.Number))
                    {
                        result.Code = 505;
                        result.Result = "";
                        result.Message = "请传入需要查询的单号！";
                    }
                    else
                    {
                        ConsoleWrite("A", "查询灵当（报价单）:", "传入（" + JsonConvert.SerializeObject(data) + "）");

                        string sql = _QueryBus.Get_Crm_MySqlQueryStateMent("Quotation", data);

                        try
                        {
                            ds = Common.MYSQLHelper.Query_New(sql, "");
                            if (ds != null && ds.Tables[0].Rows.Count > 0)
                            {
                                foreach (DataRow item in ds.Tables[0].Rows)
                                {
                                    Crm_MySqlQuotaQuery _MSDataQuery = new Crm_MySqlQuotaQuery();
                                    _MSDataQuery.Number = item["报价单号"].ToString();
                                    _MSDataQuery.MaterialID = Convert.ToInt32(item["物料ID"].ToString());
                                    _MSDataQuery.MaterialNo = item["物料编码"].ToString();
                                    _MSDataQuery.MaterialName = item["物料名称"].ToString();
                                    _MSDataQuery.Qty = Convert.ToDecimal(item["数量"].ToString());
                                    MSQuery.Add(_MSDataQuery);         
                                }
                                result.Code = 0;
                                result.Result = JsonConvert.SerializeObject(MSQuery);
                                result.Message = "";
                            }
                            else
                            {
                                result.Code = 501;
                                result.Result = "";
                                result.Message = "查无数据！";
                            }
                            ConsoleWrite("A", "查询灵当:", "返回（" + JsonConvert.SerializeObject(MSQuery) + "）");
                        }
                        catch (Exception ex)
                        {
                            result.Code = 506;
                            result.Result = "";
                            result.Message = ex.Message;
                        }
                    }

                    return JsonConvert.SerializeObject(result);

                }
                catch (Exception ex)
                {
                    ConsoleWrite("A", "查询灵当:", ex.Message);
                    result.Code = 506;
                    result.Result = "";
                    result.Message = ex.Message;
                    return JsonConvert.SerializeObject(result);
                }
            }
        }


        #endregion


        #region 3.中合誉品管理后台相关
        /// <summary>
        /// 写入中合誉品-物料
        /// </summary>
        /// <param name="Type"></param>
        /// <param name="Data"></param>
        /// <returns></returns>
        [Route("ZHYPMaterialSave"), HttpPost]
        public async Task<string> Set_ZhypMaterialSave(Crm_MaterialList Data)
        {
            IsSuccessResult isSuccess = new IsSuccessResult();
            #region 
            try
            {
                if (Data == null)
                {
                    isSuccess.Code = 506;
                    isSuccess.Result = null;
                    isSuccess.Message = "数据不可为空！";
                    return JsonConvert.SerializeObject(isSuccess);
                }

                if (Data.orgid == 1)
                {
                    CommDBId = "1";
                    Header = new Dictionary<string, string>();
                    Header.Add("region", "1");
                }
                else if (Data.orgid == 104899)
                {
                    CommDBId = "2";
                    Header = new Dictionary<string, string>();
                    Header.Add("region", "2");
                    //region: "2";
                }
                else
                {
                    isSuccess.Code = 507;
                    isSuccess.Result = null;
                    isSuccess.Message = "电商提示：登录失败！！";
                    return JsonConvert.SerializeObject(isSuccess);
                }

                string LoginJson = JsonConvert.SerializeObject(new
                {
                    login_name = usename,
                    password = usepassword,
                    region = CommDBId,
                    type = CommType
                });
                string httprs = await WebHelper.HttpPost(CommUrl + "login/loginApi", LoginJson, Header, "application/json");

                //Console.WriteLine($"调用接口：{CommUrl}login/loginApi======{LoginJson}======{JsonConvert.SerializeObject(Header)}===响应：{httprs.Substring(0,100)}");
                LoginToken token = JsonConvert.DeserializeObject<LoginToken>(httprs);

                if (token.code == 1)
                {
                    ZHYP_MaterialData _MaterialData = Data.ZHYP_MaData;
                    _MaterialData.title_acronym = DetermineCharType(_MaterialData.product_title);
                    if (string.IsNullOrWhiteSpace(_MaterialData.sku_bar_code))
                    {
                        _MaterialData.sku_bar_code = "0";
                    }

                    string jsondata = JsonConvert.SerializeObject(_MaterialData);
                    string Urls = CommUrl + "Product/productAddApiNew?token=" + token.data.user.token;

                    httprs = await WebHelper.HttpPost(Urls, jsondata, Header, "application/json");
                    Console.WriteLine($"调用接口：{Urls}======{jsondata}======{JsonConvert.SerializeObject(Header)}===响应：{httprs}");

                    DSPTResult mes = JsonConvert.DeserializeObject<DSPTResult>(httprs);

                    if (mes.code == 1)
                    {
                        DSMessage result = JsonConvert.DeserializeObject<DSMessage>(httprs);
                        NeedsResult needs = new NeedsResult();
                        isSuccess.Code = 0;
                        isSuccess.Result = result.data.id.ToString();
                        isSuccess.Message = null;
                        LogHelper.WriteLog("电商-物料", Convert.ToInt32(result.data.id.ToString()), "", 1, "金蝶写入电商", jsondata, httprs, "", "");
                    }
                    else
                    {
                        isSuccess.Code = 505;
                        isSuccess.Result = null;
                        isSuccess.Message = "电商异常：" + mes.msg;
                        LogHelper.WriteLog("电商-物料", 0, "", 0, "金蝶写入电商", jsondata, httprs, "", "");
                    }
                    return JsonConvert.SerializeObject(isSuccess);
                }
                else
                {
                    isSuccess.Code = 505;
                    isSuccess.Result = null;
                    isSuccess.Message = "电商异常：获取电商平台Token失败！！！";
                    LogHelper.WriteLog("电商-物料", 0, "", 0, "金蝶写入电商", LoginJson, httprs, "", "");
                    return JsonConvert.SerializeObject(isSuccess);
                }

            }
            catch (Exception e)
            {
                isSuccess.Code = 505;
                isSuccess.Result = null;
                isSuccess.Message = "电商异常：无法获取Token！！！";
                LogHelper.WriteLog("电商-物料", 0, "", 0, "金蝶写入电商", "", "", e.Message, "");
                return JsonConvert.SerializeObject(isSuccess);
            }
            #endregion


            #region 去除新增
            /*string LoginJson = JsonConvert.SerializeObject(new {
                login_name = usename,
                password = usepassword,
                region = 1,
                type = 1
            });
            string httprs = await WebHelper.HttpPost(CommUrl+"login/loginApi", LoginJson, Header, "application/json");
            ConsoleWrite("C","电商新增：","调用未使用");
            isSuccess.Code = 0;
            isSuccess.Result = "";
            isSuccess.Message = null;
            return JsonConvert.SerializeObject(isSuccess);*/
            #endregion

        }

        /// <summary>
        /// 修改中合誉品-物料
        /// </summary>
        /// <param name="Data"></param>
        /// <returns></returns>
        [Route("ZHYPMaterialUpSave"), HttpPost]
        public async Task<string> Set_ZhypMaterialUpdate(Crm_MaterialList Data)
        {
            IsSuccessResult isSuccess = new IsSuccessResult();
            #region
            try
            {
                if (Data == null)
                {
                    isSuccess.Code = 506;
                    isSuccess.Result = null;
                    isSuccess.Message = "数据不可为空！";
                    return JsonConvert.SerializeObject(isSuccess);
                }

                if (Data.orgid == 1)
                {
                    CommDBId = "1";
                    Header = new Dictionary<string, string>();
                    Header.Add("region", "1");
                }
                else if (Data.orgid == 104899)
                {
                    CommDBId = "2";
                    Header = new Dictionary<string, string>();
                    Header.Add("region", "2");
                    //region: "2";
                }
                else
                {
                    isSuccess.Code = 507;
                    isSuccess.Result = null;
                    isSuccess.Message = "电商提示：登录失败！！";
                    return JsonConvert.SerializeObject(isSuccess);
                }

                string LoginJson = JsonConvert.SerializeObject(new
                {
                    login_name = usename,
                    password = usepassword,
                    region = CommDBId,
                    type = CommType
                });
                string httprs = await WebHelper.HttpPost(CommUrl + "login/loginApi", LoginJson, Header, "application/json");

                LoginToken token = JsonConvert.DeserializeObject<LoginToken>(httprs);

                if (token.code == 1)
                {
                    string SelectJson = JsonConvert.SerializeObject(new
                    {
                        id = Data.DSID
                    });
                    httprs = await WebHelper.HttpPost(CommUrl + "Product/productInfoApi?token=" + token.data.user.token, SelectJson, Header, "application/json");

                    if (!string.IsNullOrEmpty(httprs))
                    {
                        DSMaterimalUp materimalUp = JsonConvert.DeserializeObject<DSMaterimalUp>(httprs);
                        if (materimalUp.code == 1)
                        {
                            DS_UpMaterimalBus _UpMaterimalBus = new DS_UpMaterimalBus();

                            string UpStr = _UpMaterimalBus.DSUpMaterimal(materimalUp, Data.ZHYP_MaData);
                            httprs = await WebHelper.HttpPost(CommUrl + "Product/productEditApiNew?token=" + token.data.user.token, UpStr, Header, "application/json");
                            //https://123.60.98.252/admin/Product/productEditApiNew?token=
                            DSPTResult mes = JsonConvert.DeserializeObject<DSPTResult>(httprs);

                            if (mes.code == 1)
                            {
                                //DSMessage result = JsonConvert.DeserializeObject<DSMessage>(httprs);
                                LogHelper.WriteLog("电商-物料-修改", Convert.ToInt32(Data.DSID), "", 1, "金蝶写入电商", UpStr, httprs, "", "");
                                NeedsResult needs = new NeedsResult();
                                isSuccess.Code = 0;
                                isSuccess.Result = Data.DSID.ToString();
                                isSuccess.Message = null;
                            }
                            else
                            {
                                isSuccess.Code = 505;
                                isSuccess.Result = null;
                                isSuccess.Message = "电商异常：" + mes.msg;
                                LogHelper.WriteLog("电商-物料-修改", 0, "", 0, "金蝶写入电商", UpStr, httprs, "", "");
                            }
                            if (Data.orgid != 1 || mes.code != 1)
                            {
                                return JsonConvert.SerializeObject(isSuccess);
                            }
                            else {
                               
                                    Console.WriteLine("物料修改 星岛扩展逻辑 开始============");

                                    CommDBId = "3";
                                    Header = new Dictionary<string, string>();
                                    Header.Add("region", "3");
                                    LoginJson = JsonConvert.SerializeObject(new
                                    {
                                        login_name = usename,
                                        password = usepassword,
                                        region = CommDBId,
                                        type = CommType
                                    });
                                    httprs = await WebHelper.HttpPost(CommUrl + "login/loginApi", LoginJson, Header, "application/json");
                                    Console.WriteLine($"调用接口：{CommUrl}login/loginApi======{LoginJson}======{JsonConvert.SerializeObject(Header)}===响应：{httprs.Substring(0, 100)}");

                                    token = JsonConvert.DeserializeObject<LoginToken>(httprs);

                                    if (token.code == 1)
                                    {
                                         SelectJson = JsonConvert.SerializeObject(new
                                        {
                                            id = Data.DSID
                                        });
                                        httprs = await WebHelper.HttpPost(CommUrl + "Product/productInfoApi?token=" + token.data.user.token, SelectJson, Header, "application/json");
                                        Console.WriteLine($"调用接口：{CommUrl + "Product/productInfoApi?token=" + token.data.user.token}======{SelectJson}======{JsonConvert.SerializeObject(Header)}===响应：{httprs}");

                                        if (!string.IsNullOrEmpty(httprs))
                                        {
                                             materimalUp = JsonConvert.DeserializeObject<DSMaterimalUp>(httprs);
                                            if (materimalUp.code == 1)
                                            {
                                                 _UpMaterimalBus = new DS_UpMaterimalBus();

                                                 UpStr = _UpMaterimalBus.DSUpMaterimal(materimalUp, Data.ZHYP_MaData);
                                                httprs = await WebHelper.HttpPost(CommUrl + "Product/productXdEditApiNew?token=" + token.data.user.token, UpStr, Header, "application/json");
                                                //https://123.60.98.252/admin/Product/productEditApiNew?token=
                                                 mes = JsonConvert.DeserializeObject<DSPTResult>(httprs);

                                                if (mes.code == 1)
                                                {
                                                    //DSMessage result = JsonConvert.DeserializeObject<DSMessage>(httprs);
                                                    LogHelper.WriteLog("电商-物料-修改-星岛", Convert.ToInt32(Data.DSID), "", 1, "金蝶写入电商", UpStr, httprs, "", "");
                                                    NeedsResult needs = new NeedsResult();
                                                    isSuccess.Code = 0;
                                                    isSuccess.Result = Data.DSID.ToString();
                                                    isSuccess.Message = null;
                                                }
                                                else
                                                {
                                                    isSuccess.Code = 505;
                                                    isSuccess.Result = null;
                                                    isSuccess.Message = "电商异常：" + mes.msg;
                                                    LogHelper.WriteLog("电商-物料-修改-星岛", 0, "", 0, "金蝶写入电商", UpStr, httprs, "", "");
                                                }
                                                return JsonConvert.SerializeObject(isSuccess);
                                            }
                                            else
                                            {
                                                isSuccess.Code = 505;
                                                isSuccess.Result = null;
                                                isSuccess.Message = $"电商异常：获取ID为{Data.DSID}的数据失败！！！";
                                                LogHelper.WriteLog("电商-物料-星岛", 0, "", 0, "金蝶写入电商", SelectJson, httprs, "", "");
                                                return JsonConvert.SerializeObject(isSuccess);
                                            }
                                        }
                                        else
                                        {
                                            isSuccess.Code = 505;
                                            isSuccess.Result = null;
                                            isSuccess.Message = $"电商异常：获取ID为{Data.DSID}的数据失败，数据为空！！！";
                                            LogHelper.WriteLog("电商-物料-星岛", 0, "", 0, "金蝶写入电商", SelectJson, httprs, "", "");
                                            return JsonConvert.SerializeObject(isSuccess);
                                        }

                                    }
                                    else
                                    {
                                        isSuccess.Code = 505;
                                        isSuccess.Result = null;
                                        isSuccess.Message = "电商异常：获取电商平台Token失败！！！";
                                        LogHelper.WriteLog("电商-物料-星岛", 0, "", 0, "金蝶写入电商", LoginJson, httprs, "", "");
                                        return JsonConvert.SerializeObject(isSuccess);
                                    }
                                }
                           
                        }
                        else
                        {
                            isSuccess.Code = 505;
                            isSuccess.Result = null;
                            isSuccess.Message = $"电商异常：获取ID为{Data.DSID}的数据失败！！！";
                            LogHelper.WriteLog("电商-物料", 0, "", 0, "金蝶写入电商", SelectJson, httprs, "", "");
                            return JsonConvert.SerializeObject(isSuccess);
                        }
                    }
                    else
                    {
                        isSuccess.Code = 505;
                        isSuccess.Result = null;
                        isSuccess.Message = $"电商异常：获取ID为{Data.DSID}的数据失败，数据为空！！！";
                        LogHelper.WriteLog("电商-物料", 0, "", 0, "金蝶写入电商", SelectJson, httprs, "", "");
                        return JsonConvert.SerializeObject(isSuccess);
                    }

                }
                else
                {
                    isSuccess.Code = 505;
                    isSuccess.Result = null;
                    isSuccess.Message = "电商异常：获取电商平台Token失败！！！";
                    LogHelper.WriteLog("电商-物料", 0, "", 0, "金蝶写入电商", LoginJson, httprs, "", "");
                    return JsonConvert.SerializeObject(isSuccess);
                }


                
            }
            catch (Exception ex)
            {

                throw;
            }
            #endregion

            #region 去除修改
            /*string LoginJson = JsonConvert.SerializeObject(new
            {
                login_name = usename,
                password = usepassword,
                region = 1,
                type = 1
            });
            string httprs = await WebHelper.HttpPost(CommUrl + "login/loginApi", LoginJson, Header, "application/json");
            ConsoleWrite("C", "电商修改：", "调用未使用");
            isSuccess.Code = 0;
            isSuccess.Result = "";
            isSuccess.Message = null;
            return JsonConvert.SerializeObject(isSuccess);*/
            #endregion
        }
        #endregion


        #region 中文转拼音
        /// <summary>
        /// 通过扩展方法实现
        /// </summary>
        public string GetPinYinByExtension(string str)
        {
            var result = str.ToPinyin(); return result;
        }

        /// <summary>
        /// 通过扩展方法实现
        /// </summary>
        public string GetPinyinInitialLetterByExtension(string str)
        {
            var result = str.ToPinyinInitialLetter(); return result.ToLower();
        }

        /// <summary>
        /// 汉字转中文
        /// </summary>
        /// <param name="data">字符串</param>
        /// <returns>把中文转换后返回</returns>
        public string DetermineCharType(string data)
        {
            string ArrD = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            string ArrX = "abcdefghijklmnopqrstuvwxyz";
            char[] ArrData = data.ToCharArray();

            string ReturnData = "";
            for (int i = 0; i < ArrData.Length; i++)
            {
                if (ArrD.IndexOf(ArrData[i].ToString()) > -1 || ArrX.IndexOf(ArrData[i].ToString()) > -1)
                {
                    ReturnData += ArrData[i].ToString();
                }
                else
                {
                    ReturnData += GetPinyinInitialLetterByExtension(ArrData[i].ToString());
                }
            }
            return ReturnData;

        }
        #endregion


        [Route("WriteDataAPI"), HttpPost]
        public async Task<string> WriteDataAPI(KingdeeOid oid)
        {
            try
            {
                string LoginJson = JsonConvert.SerializeObject(oid);
                string httprs = await WebHelper.HttpPost("http://localhost:5058/BPO_WebApi/WriteDataAPI", LoginJson, null, "application/json");
                return httprs;
            }
            catch (Exception)
            {
                throw;
            }
        }

        
    }
}
